import axios from 'axios'
import store from '@/store'
import { ElMessage } from 'element-plus'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  timeout: 5000
})

service.interceptors.request.use((config: any) => {
  const token = store.getters.token
  if (token) {
    config.headers.Authorization = token
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 后置拦截
service.interceptors.response.use(
  response => {
    // 业务失败，消息提示
    const { status, msg } = response.data
    if (status === 200) {
      return response.data
    } else {
      ElMessage.error(msg)
      return Promise.reject(new Error(msg))
    }
  },
  error => {
    ElMessage.error(error.message)
    return Promise.reject(error)
  }
)

export default service
